// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <boost/random/uniform_int_distribution.hpp>
#include <string>

#include <pollux/plan/input_generator.h>

using namespace kumo::pollux::plan;

namespace kumo::pollux::exec::test {

class MinMaxInputGenerator : public InputGenerator {
 public:
  explicit MinMaxInputGenerator(const std::string& name)
      : indexOfN_{indexOfN(name)} {}

  std::vector<VectorPtr> generate(
      const std::vector<TypePtr>& types,
      VectorFuzzer& fuzzer,
      FuzzerGenerator& rng,
      memory::MemoryPool* pool) override {
    // TODO Generate inputs free of nested nulls.
    if (types.size() <= indexOfN_) {
      return {};
    }

    // Make sure to use the same value of 'n' for all batches in a given Fuzzer
    // iteration.
    if (!n_.has_value()) {
      n_ = boost::random::uniform_int_distribution<int64_t>(0, 9'999)(rng);
    }

    const auto size = fuzzer.getOptions().vectorSize;

    std::vector<VectorPtr> inputs;
    inputs.reserve(types.size());
    for (auto i = 0; i < types.size() - 1; ++i) {
      inputs.push_back(fuzzer.fuzz(types[i]));
    }

    POLLUX_CHECK(
        types.back()->is_bigint(),
        "Unexpected type: {}",
        types.back()->toString());
    inputs.push_back(
        BaseVector::create_constant(BIGINT(), n_.value(), size, pool));
    return inputs;
  }

  void reset() override {
    n_.reset();
  }

 private:
  // Returns zero-based index of the 'n' argument, 1 for min and max. 2 for
  // min_by and max_by.
  static int32_t indexOfN(const std::string& name) {
    if (name == "min" || name == "max") {
      return 1;
    }

    if (name == "min_by" || name == "max_by") {
      return 2;
    }

    POLLUX_FAIL("Unexpected function name: {}", name);
  }

  // Zero-based index of the 'n' argument.
  const int32_t indexOfN_;
  std::optional<int64_t> n_;
};

} // namespace kumo::pollux::exec::test
